/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tool.messenger;

import elaborate.tool.messenger.yahoo.YahooMessengerConnection;
import java.io.FileInputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/**
 *
 * @author lendle
 */
public class MessageSenderAppThread extends Thread {

    private boolean enabled = false;
    private JTextArea log = null;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public MessageSenderAppThread(JTextArea log) {
        this.log = log;
        this.setDaemon(true);
    }

    @Override
    public void run() {
        while (true) {
            java.sql.Connection dbConn=null;
            try {
                Thread.sleep(5*60*1000);
                //Thread.sleep(10000);
                if (!this.enabled) {
                    continue;
                }
                //System.out.println(1);
                Class.forName("org.sqlite.JDBC");
                
                Properties props=new Properties();
                FileInputStream input=new FileInputStream("account.properties");
                props.load(input);
                input.close();
                
                dbConn = DriverManager.getConnection("jdbc:sqlite:messages.sqlite");

                String format = "yyyyMMddHHmm";
                SimpleDateFormat formatter = new SimpleDateFormat(format);
                String dateString = formatter.format(new Date());

                Statement stmt = dbConn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM messages where processed=0 and message_time<='" + dateString + "' order by message_time ASC");
                List<String> tobeMarkedAsPreocessed = new ArrayList<String>();
                
                YahooMessengerConnection conn=null;
                MessengerSender sender=null;
                while (rs.next()) {
                    if(conn==null){
                        conn=new YahooMessengerConnection();
                        conn.connect(props.getProperty("username"), props.getProperty("password"));
                        sender=conn.getSender();
                    }
                    tobeMarkedAsPreocessed.add(rs.getString("id"));
                    sender.sendMessage(rs.getString("destination"), new Message[]{new StringMessage(rs.getString("message"))});
                    log.append(rs.getString("id")+" is sent\r\n");
                }
                System.out.println(1);
                for (String id : tobeMarkedAsPreocessed) {
                    stmt.executeUpdate("UPDATE messages set processed=1 WHERE id=" + id);
                }

                dbConn.close();
                
                if(conn!=null){
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.append("Error: " + e.getMessage()+"\r\n");
            }finally{
                if(dbConn!=null){
                    try {
                        dbConn.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(MessageSenderAppThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
}
